<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select
        v-if="userType !== 'qudao'"
        v-model="listQuery.query_type"
        style="width: 150px"
        class="filter-item"
        @change="onChangeType"
      >
        <el-option
          v-for="item in typeOptions"
          :key="item.key"
          :label="item.label"
          :value="item.key"
        />
      </el-select>
      <el-select
        v-if="listQuery.query_type !== 1 && userType !== 'qudao'"
        v-model="listQuery.username"
        clearable
        filterable
        style="width: 150px"
        class="filter-item"
        @change="handleFilter"
      >
        <el-option
          v-for="(item, index) in dailiArr"
          :key="index"
          :label="item"
          :value="item"
        />
      </el-select>
      
      <el-date-picker
        v-model="value1"
        type="daterange"
        align="left"
        unlink-panels
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        class="filter-item pickertime"
        format="yyyy-MM-dd"
        value-format="timestamp"
        :picker-options="pickerOptions2"
        @change="handleFilter"
      />
      <a-button type="primary" size="large" @click="handleFilter">
        搜索
      </a-button>
      <a-button type="default" size="large" @click="handleCancel">
        重置
      </a-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      fit
      highlight-current-row
      style="width: 100%"
      @sort-change="sortChange"
    >
      <el-table-column v-if="userType == 'all'" key="1235" min-width="20" type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item v-for="(v, k, i) in props.row.adv_content" :label="optionPackageName[k] +' : '" :key="i">
              <el-tree :data="objectToTree(v)" :props="defaultProps" @node-click="handleNodeClick" default-expand-all></el-tree>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column
        key="1"
        label="日期"
        align="center"
        prop="time_"
        min-width="120"
      >
      </el-table-column>
      <el-table-column
        v-if="listQuery.query_type !== 1"
        key="2"
        prop="username"
        :label="listQuery.query_type === 2 ? '代理账号' : '渠道账号'"
        min-width="120"
        align="center"
      ></el-table-column>
      <el-table-column
        key="3"
        label="广告点击数量"
        align="center"
        prop="adv_count"
        min-width="120"
      >
        <template slot-scope="{ row }">
          <span v-for="(v, k, i) in row.adv_count" :key="i" class="adv_count">
            {{ click_menu[k] }} : {{ v }}
          </span>
        </template>
      </el-table-column>

    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      class="pageShow"
      :page.sync="listQuery.page"
      :page_size.sync="listQuery.page_size"
      @pagination="getList"
    />
  </div>
</template>

<script>
import {
  getProxyNameList,
  getChannelNameList,
  subordinate,
  getAdvClickList
} from "@/api/admin/admin";

import {  getPkgList} from "@/api/adv_admin/config.js"
import waves from "@/directive/waves"; // waves directive
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import {qd_List, pkgs, click_menu, adv_type} from '@/utils/index'
export default {
  name: "Report",
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "info",
        deleted: "danger",
      };
      return statusMap[status];
    },
  },
  data() {
    return {
      click_menu,
      dialogVisible: false,
      userType: this.$store.state.user.type,
      username: this.$store.state.user.name.username,
      tableKey: 0,
      list: null,
      subList: [],
      total: 0,
      listLoading: true,
      subListLoading: true,
      value1: "",
      dailiArr: [],
      countPv: "",
      countUv: "",
      countProfit: "",
      feedback_num: "",
      listQuery: {
        page: 1,
        page_size: 20,
        query_type: 1,
        username: "",
        order_field: "",
        sort: "",
        time_start: "",
        time_end: "",
      },
      sublistQuery: {
        page: 1,
        page_size: 20,
        date: "",
        qudao: "",
      },
      subTotal: 0,
      pickerOptions2: {
        shortcuts: [
          {
            text: "昨天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      typeOptions: [],
      qd_List: qd_List,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      optionPackageName: {}
    };
  },
  created() {
    this.getPkgs();
    this.getList();
  },
  mounted() {
    if (this.userType == "daili") {
      this.listQuery.query_type = 1;
      this.typeOptions = [
        { label: "按总和查看", key: 1 },
        { label: "按渠道查看", key: 3 },
      ];
    } else if (this.userType == "qudao") {
      this.listQuery.query_type = 3;
    } else {
      this.typeOptions = [
        { label: "按总和查看", key: 1 },
        { label: "按代理查看", key: 2 },
        { label: "按渠道查看", key: 3 },
      ];
    }
  },
  methods: {
    getPkgs(){
        getPkgList({data_type: '1'}).then(res => {
          if (res.STATUS == 200){
                  this.optionPackageName = res.DATA.list
              }
        })
      },
    showSub(item) {
      // 获取下级实时数据
      this.dialogVisible = true;
      this.subListLoading = true;
      if (item.time_) {
        this.sublistQuery.date = item.time_;
      }
      if (item.page) {
        this.sublistQuery.page = item.page;
        this.sublistQuery.page_size = item.limit;
      }
      subordinate(this.sublistQuery).then((res) => {
        this.subList = res.DATA.list;

        this.subListLoading = false;
        this.subTotal = res.DATA.total;
      });
    },
    handleNodeClick(data) {
      // console.log(data);
    },
    objectToTree(data){
      let d = []
      for(let key in data){
        let d1 = {
          'label': key,
          'children':[]
        }
        for(let key2 in data[key]){
          d1.children.push({
            'label': adv_type[key2] + " : 点击("+ data[key][key2]['ad_click']+")展示("+ data[key][key2]['ad_show'] +") 点击率("+ (data[key][key2]['ad_click'] /  data[key][key2]['ad_show'] * 100).toFixed(2) +"%)"
          })

        }
        d.push(d1)
      }
      // console.log(d)
      return d
    },
    objSort(obj, bigMinFlag){
      var arr = [];
      for(var x in obj){
          var tmp = {};
          tmp[x] = obj[x];
          arr.push(Object.assign({'k':x, 'v': tmp[x]},{__age:obj[x]}))
      };
      function compare(property){
          return function(a,b){
              var value1 = parseInt(a[property]);
              var value2 = parseInt(b[property]);
              if(bigMinFlag){
              return value1 - value2
              }else{
              return value2 - value1
              }
              
          }
      };
      arr.sort(compare('__age')).map((item) =>{
          delete item['__age'];
      });
      return arr;
    },
    getList(item) {
      this.listLoading = true;
      if (this.value1) {
        this.listQuery.time_start = this.value1[0] / 1000;
        this.listQuery.time_end = this.value1[1] / 1000;
      } else {
        this.listQuery.time_start = "";
        this.listQuery.time_end = "";
      }
      if (item) {
        this.listQuery.page = item.page;
        this.listQuery.page_size = item.limit;
      }

      if (this.listQuery.query_type === 1) {
        this.listQuery.username = "";
      }
      getAdvClickList(this.listQuery).then((response) => {
        // debugger;
        this.list = response.DATA.list;
      //   if (this.listQuery.query_type == 1) {
      //     this.list.unshift({
      //         phone_model_content: response.DATA.today,
      //         time_: response.DATA.datetime,
      //         type:1,
      //         username: "all"
      //     });
      //     }
      //   for(let i=0; i < this.list.length; i++ ){
      //     this.list[i].phone_m = this.objSort(this.list[i].phone_model_content)
      //   }

        this.total = response.DATA.total;
        this.listLoading = false;
        // console.log(this.list)
      });
    },
    //切换查看类型
    onChangeType() {
      // console.log('11111111111', this.listQuery.query_type)
      this.listQuery.username = "";
      if (this.listQuery.query_type == 2) {
        this.getProxyNameList();
      } else if (this.listQuery.query_type == 3) {
        this.getChannelNameList();
      }
      this.handleFilter();
    },
    //获取代理列表
    getProxyNameList() {
      getProxyNameList().then((r) => {
        this.dailiArr = r.DATA;
      });
    },
    //获取渠道列表
    getChannelNameList() {
      getChannelNameList().then((r) => {
        this.dailiArr = r.DATA;
      });
    },
  
    sortChange(data) {
      const { prop, order } = data;
      if (prop === "id") {
        this.listQuery.order_field = "day";
        if (order === "ascending") {
          this.listQuery.sort = "asc";
        } else if (order === "descending") {
          this.listQuery.sort = "desc";
        } else {
          this.listQuery.order_field = "day";
          this.listQuery.sort = "desc";
        }
        this.handleFilter();
      } else if (prop === "uv") {
        this.listQuery.order_field = "uv";
        if (order === "ascending") {
          this.listQuery.sort = "asc";
        } else if (order === "descending") {
          this.listQuery.sort = "desc";
        } else {
          this.listQuery.order_field = "day";
          this.listQuery.sort = "desc";
        }
        this.handleFilter();
      } else if (prop === null) {
        this.listQuery.order_field = "day";
        this.listQuery.sort = "desc";
        this.handleFilter();
      }
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleCancel() {
      this.value1 = "";
      this.listQuery.sort = "";
      this.listQuery.page = 1;
      this.listQuery.query_type = 1;
      this.getList();
    }
  }
};
</script>

<style scoped>
.demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 24%;
  }
.pageHidden {
  display: none;
}
@media (max-width: 550px) {
  .pageShow {
    display: none;
  }
  .pageHidden {
    display: block;
  }
  .pickertime {
    width: 100%;
  }
}
.filter-item {
  margin-bottom: 3px;
}
.adv_count{
  padding-right: 20px;
}
</style>
